package dy.com.tcp结合udp.Client;

import dy.com.tcp结合udp.Client.bean.ServerInfo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.*;

public class TCPClient {
    static void linkwith(ServerInfo serverInfo) throws IOException {
        Socket socket = new Socket();
        socket.setSoTimeout(3000);
        //连接
        socket.connect(new InetSocketAddress(InetAddress.getByName(serverInfo.getIp()), serverInfo.getPort()), 3000);

        System.out.println("客户端已经发起连接");
        todo(socket);
        socket.close();
        System.out.println("客户端已退出");

    }

    static void todo(Socket socket) throws IOException {
        boolean finish = false;

        //得到键盘输入流
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

        //得到socket输出流
        PrintStream printStream = new PrintStream(socket.getOutputStream());

        //得到socket输入流
        BufferedReader socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        while (!finish) {
            String str = bufferedReader.readLine();

            printStream.println(str);
            //从服务器读一行
            String res = socketReader.readLine();
            if(res.equals("bye")){
                finish=true;
            }else{
                System.out.println(res);
            }
        }
        printStream.close();
        socketReader.close();
        bufferedReader.close();
    }
}
